import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';

import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Radio,
  Tag,
  Select,
  InputNumber,
  Row,
  Col,
  Checkbox,
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request } from 'umi';
import moment from 'moment';
const { Option } = Select;
const ProductModal = (props: any, refs: any) => {
  const [form] = Form.useForm();
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form;
  const [code, setCode] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [items, setItems] = useState([]);
  const [userlist, setuserlist] = useState([]);
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  const getRoles = () => {
    request('/sys/role/roleList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      console.log(res);
      const rolelist = res?.data || [];
      rolelist.map((e: any, i: Number) => {
        rolelist[i]['label'] = e['roleName'];
        rolelist[i]['value'] = e['roleId'];
      });
      setItems(rolelist);
    });
  };

  const getUsers = () => {
    request('/sys/role/getOfficeTree', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      console.log(res);
      const list = res?.data || [];
      let users: any = [];
      list.map((e: any) => {
        users = users.concat(e.childrens);
      });
      let nlist = [];

      users.map((e, i) => {
        nlist.push({
          label: e.name,
          value: e.id,
        })

      })
      setuserlist(nlist);
    });
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    resetFields();
    props.callback && props.callback();
  };

  //确定
  const handleOk = () => {
    form
      .validateFields()
      .then((vals) => {
        let Obj = form.getFieldsValue();
        console.log(Obj);

        if (code) {
          Obj.userId = code;
        } else {
        }
        const url = code ? '/sys/role/editUserRole' : '/sys/role/saveRoleUser';
        request(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: Obj,
        }).then(() => {
          setIsModalVisible(false);
          handleCancel();
        });
      })
      .catch((info) => { });
  };
  const getDetail = (id: any) => {
    request('/sys/role/roleListByUserId', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        userId: id,
      },
    }).then((res) => {
      const detaildata = res?.data;
      setFieldsValue(detaildata);
      showModal();
    });
  };
  useImperativeHandle(refs, () => ({
    init: (id: any, record: any) => {
      if (id) {
        setCode(id);
        getDetail(id);
      } else {
        resetFields();
        showModal();
        getUsers();
      }
      getRoles();
      // setfileList([]);
    },
  }));
  const filterOption = (inputValue, option) => {
    console.log(inputValue);
    console.log(option);
    return option.label.indexOf(inputValue) != -1
  }
  return (
    <>
      <Modal
        title={code === '' ? '分配权限' : '分配权限'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        centered
        width={700}
        maskClosable={false}
        bodyStyle={{
          maxHeight: window.innerHeight - 150,
          overflowY: 'auto',
        }}
      >
        <Form form={form} layout="vertical" {...modalLayoutSm}>
          {code ? (
            <div>
              <Form.Item label="登录名" name="loginName">
                <Input disabled />
              </Form.Item>
              <Form.Item label="用户名" name="userName">
                <Input disabled />
              </Form.Item>
            </div>
          ) : (
            <div>
              <Form.Item label="用户" name="userList">
                <Select
                  mode="multiple"
                  allowClear
                  style={{ width: '100%' }}
                  placeholder="选择用户"
                  options={userlist}
                  filterOption={filterOption}
                >

                </Select>

              </Form.Item>
            </div>
          )}
          <Form.Item label="角色列表" name="roleList">
            <Checkbox.Group options={items} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
const AddMCom = forwardRef(ProductModal);

export default AddMCom;
